<template>
  <div>
    <!-- 新增套餐弹窗 -->
    <el-dialog
      :visible="visible"
      title="新增套餐"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="750px"
      @close="$refs.ruleForm.clearValidate()"
    >
      <el-form ref="ruleForm" :model="courseSetMealsForm" :rules="rules">
        <el-form-item label="快速复制套餐信息" label-width="130px">
          <el-select
            v-model="assignSetMealsValue"
            size="mini"
            placeholder="请选择"
            @change="assignSetMeals"
          >
            <el-option
              v-for="(item,index) in courseSetMealsData"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐名称" label-width="100px" prop="name">
          <el-input v-model="courseSetMealsForm.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="是否分佣" label-width="100px" prop="isCommission">
          <!--        <el-form-item label="是否分佣" label-width="100px">-->
          <el-radio-group v-model="courseSetMealsForm.isCommission">
            <el-radio :label="1">分佣</el-radio>
            <el-radio :label="2">不分佣</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="一级分佣" label-width="100px" prop="oneAgent">
          <!--        <el-form-item label="一级分佣" label-width="100px">-->
          <el-input v-model="courseSetMealsForm.oneAgent" placeholder="请输入一级分佣 例如：0.3" />
        </el-form-item>
        <el-form-item label="二级分佣" label-width="100px" prop="twoAgent">
          <!--        <el-form-item label="二级分佣" label-width="100px">-->
          <el-input v-model="courseSetMealsForm.twoAgent" placeholder="请输入二级分佣 例如：0.5" />
        </el-form-item>
        <el-form-item label="套餐类型" label-width="100px" prop="type">
          <el-radio-group v-model="courseSetMealsForm.type">
            <el-radio :label="1">节</el-radio>
            <el-radio :label="2">月</el-radio>
            <el-radio :label="3">季</el-radio>
            <el-radio :label="4">期</el-radio>
            <el-radio :label="5">年</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="courseSetMealsForm.type===1" label="节数" label-width="100px" prop="lessonCount">
          <el-select v-model="courseSetMealsForm.lessonCount" size="mini" placeholder="请选择">
            <el-option
              v-for="item in lessonCountOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐原价" label-width="100px" prop="originalPrice">
          <el-input v-model="courseSetMealsForm.originalPrice" :maxlength="10" placeholder="请填写套餐原价，用以与套餐现有价格作对比" />
        </el-form-item>
        <el-form-item label="套餐底价" label-width="100px" prop="floorPrice">
          <!--        <el-form-item label="套餐底价" label-width="100px">-->
          <el-input v-model="courseSetMealsForm.floorPrice" :maxlength="10" placeholder="请填写套餐底价" />
        </el-form-item>
        <el-form-item label="套餐价格" label-width="100px" prop="price">
          <el-input
            v-model="courseSetMealsForm.price"
            :maxlength="10"
            placeholder="请填写套餐价格"
            @change="changePrice"
          />
        </el-form-item>
        <el-form-item
          label="上课时间"
          label-width="100px"
          :required="courseDateData.length>0"
        >
          <el-row v-for="(date,index) in courseDateData" :key="date.key">
            <el-select v-model="date.wwValue" size="mini" style="width:100px" placeholder="请选择">
              <el-option
                v-for="item in wwOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span style="margin: 0 10px;"> 至 </span>
            <el-select v-model="date.endwwValue" size="mini" style="width:100px" placeholder="请选择">
              <el-option
                v-for="item in wwOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-time-picker
              v-model="date.startTime"
              size="mini"
              style="width:120px"
              format="HH : mm "
              value-format="timestamp"
              placeholder="开始时间"
            />-
            <el-time-picker
              v-model="date.endTime"
              size="mini"
              style="width:120px"
              format="HH : mm "
              value-format="timestamp"
              placeholder="结束时间"
            />
            <el-button
              v-if="courseDateData.length-1 ===index"
              size="mini"
              icon="el-icon-plus"
              circle
              @click="addCourseDate"
            />
            <el-button
              v-if="index !==0"
              size="mini"
              icon="el-icon-minus"
              circle
              @click="removeCourseDate(date)"
            />
          </el-row>
        </el-form-item>
        <el-form-item label="开课时间" label-width="100px" prop="startTime">
          <el-date-picker
            v-model="courseSetMealsForm.startTime"
            type="datetime"
            :picker-options="{
              disabledDate(date) {
                return date.getTime().valueOf() <= Date.now().valueOf() - 24 * 60 * 60 * 1000
              }
            }"
            value-format="timestamp"
            placeholder="开始时间"
          />
        </el-form-item>
        <el-form-item label="授课方式" label-width="100px" prop="teachingMethods">
          <el-input
            v-model.trim="courseSetMealsForm.teachingMethods"
            :maxlength="15"
            placeholder="请填写授课方式，例：1对8小班教学"
          />
        </el-form-item>
        <el-form-item
          label="购买人数限制"
          label-width="130px"
          :prop="courseSetMealsForm.isLimitQuantity===0?'isLimitQuantity':'maxQuantity'"
        >
          <el-row>
            <el-col>
              <el-radio-group v-model="courseSetMealsForm.isLimitQuantity">
                <el-radio :label="0">不限制人数</el-radio>
                <el-radio :label="1">限制人数</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
          <el-row v-show="courseSetMealsForm.isLimitQuantity===1">
            <el-col>
              <el-input
                v-model.number="courseSetMealsForm.maxQuantity"
                :maxlength="7"
                placeholder="请填写购买套餐限制的人数"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="套餐备注" label-width="100px" prop="remark">
          <el-input
            v-model.trim="courseSetMealsForm.remark"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            :maxlength="15"
            placeholder="请填写课程套餐的备注"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AddCourseDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isExperience: {
      type: Boolean,
      default: false
    },
    isAdd: {
      type: Boolean,
      default: false
    },
    courseSetMealsForm: {
      type: Object,
      default: () => {
        return {
          name: '',
          type: 1,
          wwValue: 1,
          value: 1,
          lessonCount: 1,
          lessonTime: 30, // 时长，
          isCommission: '1', // 是否分佣
          oneAgent: '', // 一级分佣
          twoAgent: '', // 二级分佣
          originalPrice: '', // 套餐原价，
          floorPrice: '', // 套餐底价
          price: null, // 套餐价格
          classTime: '', // 上课时间
          startTime: null, // 开课时间
          endTime: null, // 结束时间
          teachingMethods: '', // 授课方式
          isLimitQuantity: 0, // 购买人数限制
          courseDateData: [
            // 新增开课时间
            {
              wwValue: null,
              endwwValue: null,
              startTime: null,
              endTime: null,
              key: Date.now()
            }
          ],
          maxQuantity: null,
          remark: '' // 备注
        }
      }
    },
    courseSetMealsData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },

  data() {
    const validatePass = (rule, value, callback) => {
      // console.log(value, this.courseSetMealsForm.price, 'value')
      const priceReg = /^0\.([1-9]|\d[1-9])$|^[1-9]\d{0,6}\.\d{0,2}$|^[1-9]\d{0,6}$/
      if (!priceReg.test(value)) {
        callback(new Error('套餐价格必须为正数，整数位最大为7位'))
        // this.courseSetMealsForm.originalPrice = null
      } else {
        if (Number(value) < Number(this.courseSetMealsForm.price)) {
          callback(new Error('套餐原价必须大于套餐价格'))
        } else {
          this.$refs.ruleForm.validateField('price')
        }
        callback()
      }
    }
    const validatePrice = (rule, value, callback) => {
      const priceReg = /^0\.([1-9]|\d[1-9])$|^0$|^[1-9]\d{0,6}\.\d{0,2}$|^[1-9]\d{0,6}$/
      if (!priceReg.test(value)) {
        // alert('请输入正确的产品价格:整数或者保留两位小数')
        callback(new Error('套餐价格必须为正数，整数位最大为七位,小数位最大为两位'))
        // this.courseSetMealsForm.originalPrice = null
      } else {
        if (this.isExperience) {
          if (Number(value) > Number(this.courseSetMealsForm.originalPrice)) {
            callback(new Error('套餐价格必须小于套餐原价'))
          }
        }
        callback()
      }
    }
    return {
      assignSetMealsValue: null,
      rules: {
        name: [
          { required: true, message: '请输入套餐名称', trigger: 'blur' },
          {
            min: 0,
            max: 30,
            message: '长度在 0 到 30 个字符',
            trigger: 'change'
          }
        ],
        oneAgent: [
          { required: true, message: '请填写一级分佣', trigger: 'blur' }
        ],
        twoAgent: [
          { required: true, message: '请填写二级分佣', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择套餐类型', trigger: 'blur' }
        ],
        isCommission: [
          { required: true, message: '请选择分佣状态', trigger: 'change' }
        ],
        lessonCount: [
          { required: true, message: '请选择节数', trigger: 'change' }
        ],
        lessonTime: [
          { required: true, message: '请选择时长', trigger: 'change' }
        ],
        originalPrice: [
          { required: true, validator: validatePass, trigger: 'change' }
        ],
        floorPrice: [
          { required: true, message: '请填写套餐底价', trigger: 'blur' }
        ],
        price: [{ required: true, validator: validatePrice, trigger: 'change' }],
        classTime: [
          {
            required: true,
            message: '请输入上课时间，例：每周六9点到18点',
            trigger: 'change'
          }
        ],
        startTime: [
          {
            type: 'date',
            required: true,
            message: '请输入开课时间',
            trigger: 'change'
          }
        ],
        teachingMethods: [
          {
            required: true,
            message: '请输入授课方式，例：1对8小班教学',
            trigger: 'change'
          }
        ],
        isLimitQuantity: [
          { required: true, message: '请选择一项', trigger: 'change' }
        ],
        maxQuantity: [
          { required: true, message: '请输入购买人数限制', trigger: 'change' },
          { type: 'number', message: '请输入数字', trigger: 'change' }
        ]
      },
      options: [
        {
          label: '周末课',
          value: 1
        },
        {
          label: '周一课',
          value: 2
        }
      ],
      courseDateData: [
        {
          wwValue: 1,
          endwwValue: 6,
          startTime: 2,
          // endTime: 3
          endTime: new Date(new Date(new Date().toLocaleDateString()).getTime() + 21 * 60 * 60 * 1000)
        }
      ],
      // 周一至周日
      wwOptions: [
        {
          label: '每周一',
          value: 1
        },
        {
          label: '每周二',
          value: 2
        },
        {
          label: '每周三',
          value: 3
        },
        {
          label: '每周四',
          value: 4
        },
        {
          label: '每周五',
          value: 5
        },
        {
          label: '每周六',
          value: 6
        },
        {
          label: '每周日',
          value: 7
        }
      ],
      // 节数
      lessonCountOptions: [],
      // 每节时长
      lessonTimeOptions: [
        {
          label: '30分钟',
          value: 30
        },
        {
          label: '40分钟',
          value: 40
        },
        {
          label: '45分钟',
          value: 45
        },
        {
          label: '1小时',
          value: 60
        },
        {
          label: '1小时30分钟',
          value: 90
        },
        {
          label: '2小时',
          value: 120
        },
        {
          label: '2小时30分钟',
          value: 150
        },
        {
          label: '3小时',
          value: 180
        }
      ],
      // 是否限制购买人数
      peopleNum: 3
    }
  },
  computed: {},
  watch: {
    isAdd(v) {
      if (v) {
        // this.resetForm()
      }
    },
    'courseSetMealsForm.isLimitQuantity'(val) {
      if (val === 0) {
        this.courseSetMealsForm.maxQuantity = null
      }
    }
  },
  created() {
    if (this.courseSetMealsForm.isLimitQuantity) {
      this.peopleNum = 1
    }
    for (let i = 1; i <= 250; i++) {
      this.lessonCountOptions.push({
        label: `${i}节`,
        value: i
      })
    }
  },
  methods: {
    changePrice() {
      // const price = this.courseSetMealsForm.price
      // if (isNaN(price)) {
      //   this.courseSetMealsForm.price = null
      //   return
      // }
      // this.courseSetMealsForm.price = this.fomatFloat(price)
    },
    // 复制套餐
    assignSetMeals(id) {
      const row = this.courseSetMealsData.find(i => i.id === id)
      const data = Object.assign({}, row)
      data.id = new Date().valueOf()
      this.$emit('update:courseSetMealsForm', data)
    },
    // 新增上课时间
    addCourseDate() {
      this.courseDateData.push({
        wwValue: null,
        endwwValue: null,
        startTime: null,
        endTime: null,
        key: Date.now()
      })
    },
    // 删除上课时间
    removeCourseDate(date) {
      const index = this.courseDateData.indexOf(date)
      if (index !== -1) {
        this.courseDateData.splice(index, 1)
      }
    },
    close() {
      this.$emit('update:visible', false)
    },
    confirm() {
      // console.log(this.courseSetMealsForm.courseDateData)
      this.courseSetMealsForm.courseDateData = this.courseDateData
      // this.courseSetMealsForm.originalPrice = Number(this.courseSetMealsForm.originalPrice)
      // this.courseSetMealsForm.price = Number(this.courseSetMealsForm.price)
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let week = []
          let endwwValue = []
          let stime = []
          let etime = []
          const t = []
          this.courseDateData.forEach(i => {
            week = this.wwOptions.find(j => j.value === i.wwValue).label
            endwwValue = this.wwOptions.find(k => k.value === i.endwwValue).label
            stime = this.$options.filters.parseTime(i.startTime, '{h}:{i}')
            etime = this.$options.filters.parseTime(i.endTime, '{h}:{i}')
            t.push(`${week} 至 ${endwwValue} ${stime}-${etime}`)
          })

          this.courseSetMealsForm.classTime = t.join(',')
          console.log(this.courseSetMealsForm)
          this.$emit('confirm', this.courseSetMealsForm)
          this.$emit('update:visible', false)
        } else {
          return false
        }
      })
    },
    async resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    // 保留小数点后两位
    fomatFloat(v) {
      return (parseInt(v * 100) / 100).toFixed(2)
    }
  }
}
</script>
<style lang='scss'  scoped>
/deep/.el-input--medium .el-input__inner {
  width: 300px;
}
.dialog-footer {
  text-align: center;
}
</style>
